import {reactive, ref} from "vue";
import {checkFildsStore} from "@/stores/modules/checkFilds";

/**
 * 将一个数转换为 100,000,000.00 这样
 */

export const addSeparator = (num) => {
  if (typeof num === 'undefined' || num === null) return '0.00';

  let parsedNumber;
  if (typeof num === 'string') {
    parsedNumber = parseFloat(num);
    if (isNaN(parsedNumber)) return '0.00'; // 处理无效字符串
  } else {
    parsedNumber = num;
  }

  return parsedNumber.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 6,
  });
};




/**
 * @description 扁平化数组对象(主要用来处理路由菜单)
 * @param {Array} menuList 所有菜单列表
 * @return array
 */
export const getFlatArr = menuList => {
  let newMenuList = JSON.parse(JSON.stringify(menuList))
  return newMenuList.reduce((pre, current) => {
    let flatArr = [...pre, current]
    if (current.children) flatArr = [...flatArr, ...getFlatArr(current.children)]
    return flatArr
  }, [])
}

/**
 * @description 使用递归，过滤出需要渲染在左侧菜单的列表（剔除 isHide == true 的菜单）
 * @param {Array} menuList 所有菜单列表
 * @return array
 * */
export const getShowMenuList = menuList => {
  let newMenuList = JSON.parse(JSON.stringify(menuList))
  return newMenuList.filter(item => {
    item.children?.length && (item.children = getShowMenuList(item.children))
    return !item.meta?.isHide
  })
}

/**
 * @description 递归找出所有面包屑存储到 pinia 中
 * @param {Array} menuList 所有菜单列表
 * @param {Object} result 输出的结果
 * @param {Array} parent 父级菜单
 * @returns object
 */
export const getAllBreadcrumbList = (menuList, result = {}, parent = []) => {
  for (const item of menuList) {
    result[item.path] = [...parent, item]
    if (item.children?.length) getAllBreadcrumbList(item.children, result, result[item.path])
  }
  return result
}


// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @description 生成随机数
 * @param {Number} min 最小值
 * @param {Number} max 最大值
 * @return number
 */
export const randomNum = (min, max) => Math.floor(Math.random() * (min - max) + max)



// let resultArr= reactive([])//存放子组件的数组
// let errListMsg =ref("")//用来存储错误提示
//这个方法是固定的，用来创建 Promise 实例，为多个组件校验使用
export const checkForm = (formChild,checkFild) =>{
  formChild.validate((valid,fields)=>{
    if (valid) {

      //resolve()
    }else{

      Object.keys(fields).forEach((v,index)=>{
        if (index==0) {

          const PropName = fields[v][0].field
          formChild.scrollToField(PropName)
          checkFild.setData(PropName)
          // errListMsg.value = fields[v][0].message
        }
      })
      //reject()
    }
  })
}


export const  debounce=(func, wait, immediate)=> {

  let timeout; // 定义一个计时器变量，用于延迟执行函数
  return function (...args) { // 返回一个包装后的函数
    const context = this; // 保存函数执行上下文对象
    const later = function () { // 定义延迟执行的函数
      timeout = null; // 清空计时器变量
      if (!immediate) func.apply(context, args); // 若非立即执行，则调用待防抖函数
    };
    const callNow = immediate && !timeout; // 是否立即调用函数的条件
    clearTimeout(timeout); // 清空计时器
    timeout = setTimeout(later, wait); // 创建新的计时器，延迟执行函数
    if (callNow) func.apply(context, args); // 如果满足立即调用条件，则立即执行函数
  };
}


// 计算时间差
export const  dateDiff=(date1,date2)=> {
  let date1Str = date1.split("-");//将日期字符串分隔为数组,数组元素分别为年.月.日
//根据年 . 月 . 日的值创建Date对象
  let date1Obj = new Date(date1Str[0],(date1Str[1]-1),date1Str[2]);
  let date2Str = date2.split("-");
  let date2Obj = new Date(date2Str[0],(date2Str[1]-1),date2Str[2]);
  let t1 = date1Obj.getTime();
  let t2 = date2Obj.getTime();
  let dateTime = 1000*60*60*24; //每一天的毫秒数
  let minusDays = Math.floor(((t2-t1)/dateTime));//计算出两个日期的天数差
  let days = Math.abs(minusDays);//取绝对值
  return minusDays;
}

//权限校验
export const checkPermission = (value,roleList) => {
  //[{"text":"新增","click":"","img":"/Content/img/Add.jpg","disable":true,"id":"新增"},{"text":"修改","click":"","img":"/Content/img/update.png","disable":true,"id":"修改"},{"text":"删除","click":"","img":"/Content/img/delete.png","disable":true,"id":"删除"}]
  let flag = false;
  if(roleList==undefined|| roleList.length<=0)
  {
     return false;
  }
  for (let i = 0; i < roleList.length; i++) {
    if (roleList[i].id === value) {
      flag = true;
      break;
    }
  }
  return flag;
}

/**
 * 禁用今天之后的日期
 * @param time
 * @returns {boolean}
 */
export const disabledDate = (time) => {
  const today = new Date();
  const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
  const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);

  return time.getTime() > today.getTime() ||
      time.getTime() < startOfMonth.getTime() ||
      time.getTime() > endOfMonth.getTime();
};
